<template>
	<view class="login">
		<view class="login-info">
			<view class="login-info_logo">
				<uv-image width="120" height="120" src="/static/logo.png"></uv-image>
			</view>
		</view>
		<view class="login-form">
			<uv-form :model="loginForm">
				<uv-form-item label="" prop="account">
					<uv-input v-model="loginForm.account" placeholder="输入账号"></uv-input>
				</uv-form-item>
				<uv-form-item label="" prop="password">
					<uv-input type="password" v-model="loginForm.password" placeholder="输入密码"></uv-input>
				</uv-form-item>
				<uv-form-item label="" prop="code">
					<uv-input type="number" v-model="loginForm.code" placeholder="输入验证码"></uv-input>
					<template v-slot:right>
						<view class="" style="margin-left: 30rpx;" @click="getCode">
							<uv-image width="108" height="36" :src="svgCode"></uv-image>
						</view>
					</template>
				</uv-form-item>
				<uv-form-item label="" prop="">
					<uv-button class="login-form_submit" type="primary" text="登录" :loading="submiting"
						@click="onLogin"></uv-button>
				</uv-form-item>
				<!-- #ifdef MP-WEIXIN -->
				<uv-form-item label="" prop="">
					<uv-button class="login-form_submit-wx" type="success" :loading="wxLoading" @click="onWXLogin"
						text="一键授权登陆"></uv-button>
				</uv-form-item>
				<!-- #endif -->
			</uv-form>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive } from "vue";
	import { captcha } from "@/api/index"
	import useAppStore from "@/store/app"
	import type { LoginForm } from "@/types";
	import { onLoad } from "@dcloudio/uni-app";

	const appStore = useAppStore()


	var submiting = ref(false)
	var loginForm = reactive<LoginForm>({
		key: "",
		code: "",
		account: "",
		password: ""
	})

	onLoad(() => {
		getCode()
	})

	// 登录
	async function onLogin() {
		if (submiting.value) return
		try {
			submiting.value = true
			await appStore.login(loginForm)
			await appStore.info()
			toIndexPage()
		} catch (error) {
			//TODO handle the exception
			submiting.value = false
			loginForm.code = ""
			getCode()
		}
	}

	// 验证码
	var svgCode = ref()
	async function getCode() {
		try {
			var res : any = await captcha()
			svgCode.value = res.data.image
			loginForm.key = res.data.key
		} catch (err) {
			console.log(err)
		}
	}

	var wxLoading = ref(false)
	// 微信小程序登录
	async function onWXLogin() {
		try {
			wxLoading.value = true
			await appStore.loginWx()
			await appStore.info()
			toIndexPage()
			wxLoading.value = false
		} catch (error) {
			//TODO handle the exception
			wxLoading.value = false
			console.log(error)
		}
	}

	function toIndexPage() {
		uni.reLaunch({
			url: "/pages/index/index"
		})
	}
</script>

<style lang="scss" scoped>
	.login {
		padding: 40rpx;
		background-color: white;

		&-form {
			width: 80%;
			margin: 0 auto;

			&_submit,
			&_submit-wx {
				width: 100%;
			}

		}

		&-info {
			width: 80%;
			margin: 50rpx auto;

			&_logo {
				margin: 0 auto;
				width: max-content;
			}
		}
	}
</style>